package com.hdsx.spring.tomcat.handler;

import com.hdsx.spring.tomcat.core.TomcatServer;
import com.hdsx.spring.tomcat.request.HttpServletRequest;
import com.hdsx.spring.tomcat.response.HttpServletResponse;
import com.hdsx.spring.tomcat.servlet.HttpServlet;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;

/**
 * @author 占贤银
 * time 2024/8/16 16:28
 * description 生命之灯因热情而点燃，生命之舟因拼搏而前行
 */
public class HttpHandler extends SimpleChannelInboundHandler<HttpRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext cx, HttpRequest httpRequest) {
        try {
            String url = httpRequest.uri();
            if (url.endsWith("favicon.ico")) {
                return;
            }
            HttpMethod method = httpRequest.method();
            // 获取请求参数
            QueryStringDecoder decoder = new QueryStringDecoder(url);
            HttpServletRequest request = new HttpServletRequest(url, method.toString());
            HttpServletResponse response = new HttpServletResponse(cx);
            HttpServlet instance = TomcatServer.queryClassNameByPattern(request.getUrl());
            if (instance == null) {
                response.write("<h1 style='color:red;'>您好，找不到指定的页面！</h1>");
                return;
            }
            instance.service(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}